package com.ruoyi.common.utils.mybatis;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 员工性别类型处理器 - 将数据库中的employee.gender映射到SysUser.sex
 */
@MappedTypes(String.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class EmployeeGenderTypeHandler extends BaseTypeHandler<String> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        // 用于写入数据库，根据SysUser.sex设置employee.gender
        switch (parameter) {
            case "0": // 男
                ps.setString(i, "male");
                break;
            case "1": // 女
                ps.setString(i, "female");
                break;
            default: // 未知
                ps.setString(i, "other");
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 从数据库读取时，将employee.gender映射到SysUser.sex
        String gender = rs.getString(columnName);
        if (gender == null) {
            return "2"; // 默认为未知
        }
        switch (gender) {
            case "male":
                return "0"; // 男
            case "female":
                return "1"; // 女
            default:
                return "2"; // 其他
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String gender = rs.getString(columnIndex);
        if (gender == null) {
            return "2";
        }
        switch (gender) {
            case "male":
                return "0";
            case "female":
                return "1";
            default:
                return "2";
        }
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String gender = cs.getString(columnIndex);
        if (gender == null) {
            return "2";
        }
        switch (gender) {
            case "male":
                return "0";
            case "female":
                return "1";
            default:
                return "2";
        }
    }
}